﻿namespace SFWS.XHandler.Core
{
    using Microsoft.Practices.EnterpriseLibrary.Logging;
    using SFWS.XHandler.Core.Properties;
    using SFWS.XJSON.Core;
    using System;
    using System.Collections.Generic;
    using System.Collections.Specialized;
    using System.Configuration;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Text;
    using System.Web;

    public static class AppUtility
    {
        private static List<string> excludetypes = null;
        private static Random random = new Random();
        private static List<string> validexcludetypes = null;

        internal static bool containsLogEx(string url)
        {
            string confValue = GetConfValue(Resources.ConfSectionName, Resources.ConfKey_LogExclude);
            if (!string.IsNullOrEmpty(confValue))
            {
                string[] strArray = confValue.Split(new char[] { '|' });
                foreach (string str2 in strArray)
                {
                    if (!string.IsNullOrEmpty(str2) && url.Contains(str2))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        internal static string ContextValidate(HttpContext context, Type type)
        {
            if (IsValidExclude(type) || IsLoginExclude(type))
            {
                return null;
            }
            string confValue = GetConfValue(Resources.ConfSectionName, Resources.ConfKey_Validator);
            if (string.IsNullOrEmpty(confValue))
            {
                return confValue;
            }
            IContextValidator validator = null;
            try
            {
                validator = (IContextValidator) Type.GetType(confValue, false).GetConstructor(Type.EmptyTypes).Invoke(null);
            }
            catch
            {
            }
            if (validator == null)
            {
                return Resources.MsgNoValidtor;
            }
            validator.Context = context;
            if (!validator.IsValid)
            {
                return validator.ErrorMessage;
            }
            return "";
        }

        public static object CreateDefaultObject(Type type)
        {
            try
            {
                return type.GetConstructor(Type.EmptyTypes).Invoke(null);
            }
            catch
            {
                return null;
            }
        }

        public static string GetConfValue(string section, string key)
        {
            object obj2 = ConfigurationManager.GetSection(section);
            try
            {
                return ((NameValueCollection) obj2)[key];
            }
            catch
            {
                return null;
            }
        }

        internal static string HtmlEncode(string s)
        {
            return HttpUtility.HtmlEncode(s).Replace("'", "&#39;");
        }

        internal static bool IsLoginExclude(Type type)
        {
            try
            {
                string fullName = type.FullName;
                if (excludetypes == null)
                {
                    string[] strArray = (Resources.LoginExcludeHandlers + "," + GetConfValue(Resources.ConfSectionName, Resources.ConfKey_Excludes)).Split(new char[] { ',' });
                    excludetypes = new List<string>();
                    for (int i = 0; i < strArray.Length; i++)
                    {
                        string item = strArray[i].Trim();
                        if ((item != "") && !excludetypes.Contains(item))
                        {
                            excludetypes.Add(item);
                        }
                    }
                }
                return excludetypes.Contains(fullName);
            }
            catch
            {
                return false;
            }
        }

        internal static bool IsValidExclude(Type type)
        {
            try
            {
                string fullName = type.FullName;
                if (validexcludetypes == null)
                {
                    string[] strArray = (Resources.LoginExcludeHandlers + "," + GetConfValue(Resources.ConfSectionName, Resources.ConfKey_ValidExcludes)).Split(new char[] { ',' });
                    validexcludetypes = new List<string>();
                    for (int i = 0; i < strArray.Length; i++)
                    {
                        string item = strArray[i].Trim();
                        if ((item != "") && !validexcludetypes.Contains(item))
                        {
                            validexcludetypes.Add(item);
                        }
                    }
                }
                return validexcludetypes.Contains(fullName);
            }
            catch
            {
                return false;
            }
        }

        internal static int Log(Exception ex)
        {
            LogEntry log = new LogEntry();
            int num = random.Next(0x1869f);
            log.Title = string.Format("Exception [{0}]", num);
            log.Message = string.Format("{0}", ex);
            log.Severity = TraceEventType.Error;
            Logger.Write(log);
            return num;
        }

        internal static void Log(string errorcode)
        {
            LogEntry log = new LogEntry();
            HttpRequest request = HttpContext.Current.Request;
            if (!containsLogEx(request.RawUrl))
            {
                log.Title = string.Format("[{0}] {1} {2}:{3} {4}", new object[] { errorcode, request.RawUrl, request.UserHostAddress, request.Params["REMOTE_PORT"], HttpContext.Current.Session.SessionID });
                string str = nvConvert(request.Form);
                log.Message = string.Format("{0}{1}", (request.UrlReferrer == null) ? "" : (request.UrlReferrer.PathAndQuery + ((str.Length > 0) ? "\r\n" : "")), str);
                if (log.Message.Length > 0)
                {
                    log.Message = "\r\n" + log.Message;
                }
                Logger.Write(log);
            }
        }

        public static void Notify404()
        {
            Notify404(Resources.Error404);
        }

        public static void Notify404(string desc)
        {
            NotifyErrorStatus(400, desc);
        }

        public static void Notify500()
        {
            NotifyErrorStatus(500, Resources.Error500);
        }

        public static void Notify500(string message)
        {
            NotifyErrorStatus(500, message);
        }

        public static void NotifyAccessInvalid()
        {
            NotifyResponse(HandlerErrorType.AccessInvalid, Resources.MsgAccessInvalid, Resources.ConfKey_MsgAccessInvalid, Resources.ConfKey_PageAccessInvalid);
        }

        public static void NotifyErrorStatus(int statusCode, string statusDesc)
        {
            HttpContext.Current.Response.StatusCode = statusCode;
            HttpContext.Current.Response.StatusDescription = statusDesc;
        }

        public static void NotifyLogin()
        {
            NotifyResponse(HandlerErrorType.NeedLogin, Resources.MsgLoginNotify, Resources.ConfKey_MsgLoginNotify, Resources.ConfKey_PageLoginNotify);
        }

        private static void NotifyResponse(HandlerErrorType errorType, string defaultMsg, string msgConfKey, string redirectUrlConfKey)
        {
            JsonSerializer serializer = new JsonSerializer();
            StringBuilder builder = new StringBuilder();
            string confValue = GetConfValue(Resources.ConfSectionName, msgConfKey);
            if (string.IsNullOrEmpty(confValue))
            {
                confValue = defaultMsg;
            }
            builder.AppendFormat(Resources.JsLoginNotify, serializer.Serialize(confValue), serializer.Serialize(LoginPage));
            string s = builder.ToString();
            if (!string.IsNullOrEmpty(HttpContext.Current.Request.Params["HTTP_X_REQUESTED_WITH"]))
            {
                HttpContext.Current.Response.AppendHeader(Resources.Json_HeaderName, serializer.Serialize(new JsonObject().Add("error", new JsonObject().Add("loginPage", LoginPage).Add("errorType", errorType).Add("message", confValue))));
            }
            else
            {
                string str3 = GetConfValue(Resources.ConfSectionName, redirectUrlConfKey);
                if (!string.IsNullOrEmpty(str3))
                {
                    HttpContext.Current.Response.Redirect(string.Format("{0}{1}", AppPath, str3), true);
                }
                else if (HttpContext.Current.Request.AcceptTypes.Contains<string>("text/javascript") || HttpContext.Current.Request.AcceptTypes.Contains<string>("application/javascript"))
                {
                    HttpContext.Current.Response.Write(s);
                }
                else
                {
                    HttpContext.Current.Response.Write(string.Format("<script>{0}</script>", s));
                }
            }
        }

        private static string nvConvert(NameValueCollection nv)
        {
            StringBuilder builder = new StringBuilder();
            foreach (string str in nv.AllKeys)
            {
                builder.AppendFormat("{0}:{1},", str, nv[str]);
            }
            if (nv.AllKeys.Length > 0)
            {
                builder.Length--;
            }
            return ((builder.Length > 0) ? builder.Insert(0, "{").Append("}").ToString() : "");
        }

        public static void WriteUrlContent(string url)
        {
            int num;
            Stream stream = new WebClient().OpenRead(url);
            List<byte> list = new List<byte>();
            while ((num = stream.ReadByte()) != -1)
            {
                list.Add((byte) num);
            }
            HttpContext.Current.Response.Write(Encoding.Default.GetString(list.ToArray()));
        }

        public static string AppPath
        {
            get
            {
                return ((HttpContext.Current.Request.ApplicationPath == "/") ? "" : HttpContext.Current.Request.ApplicationPath);
            }
        }

        public static string LoginPage
        {
            get
            {
                return (((HttpContext.Current.Request.ApplicationPath == "/") ? "" : HttpContext.Current.Request.ApplicationPath) + GetConfValue(Resources.ConfSectionName, Resources.ConfKey_PageLogin));
            }
        }
    }
}

